﻿package zz.app.ustbgsmanager.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;

import zz.app.ustbgsmanager.fragments.TeachingAssessmentFragment;
import zz.app.ustbgsmanager.utils.GSManager;
import zz.app.ustbgsmanager.fragments.IndexFragment;
import zz.app.ustbgsmanager.interfaces.OnIndexButtonClickedListener;
import zz.app.ustbgsmanager.fragments.QueryCourseFragment;
import zz.app.ustbgsmanager.fragments.QueryScoreFragment;
import zz.app.ustbgsmanager.R;
import zz.app.ustbgsmanager.beans.querycourse.AccessInfo;
import zz.app.ustbgsmanager.beans.querycourse.CoursesInTerm;
import zz.app.ustbgsmanager.beans.querycourse.Term;
import zz.app.ustbgsmanager.interfaces.OnQueryScoreFailedListener;
import zz.app.ustbgsmanager.beans.queryscore.Scores;
import zz.app.ustbgsmanager.utils.NetworkUtils;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    public static final int DRAWER_ACTION_NONE = 0;
    public static final int DRAWER_ACTION_LOGOUT = 1;
    public static final int DRAWER_ACTION_ABOUT = 2;
    GSManager manager;
    Button btnLogout;
    Handler handler;
    Context context;
    BroadcastReceiver receiver;
    TextView tvCurrentUser;
    DrawerLayout drawer;
    NavigationView navigationView;
    IndexFragment indexFragment;
    QueryScoreFragment queryScoreFragment;
    QueryCourseFragment queryCourseFragment;
    TeachingAssessmentFragment teachingAssessmentFragment;
    FragmentManager fragmentManager;
    FrameLayout frameLayout;
    Snackbar sbQueryCourse;
    Snackbar sbTeachingAssessment;
    int drawerAction;
    boolean isIndex = true;
    boolean almostQuit = false;
    boolean isChanging = false;
    Fragment currentFragment;
    TextView tvCurrentUserName;
    TextView tvCurrentTerm;
    long timeStamp=-1;
    ArrayList<Fragment> fragments = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        fragments.clear();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {

            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                if (drawerAction == DRAWER_ACTION_LOGOUT) {
                    logout();
                }else if(drawerAction==DRAWER_ACTION_ABOUT){
                    about();
                }
                drawerAction = DRAWER_ACTION_NONE;
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        toggle.syncState();
        navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        init();
    }

    private void index() {
        if (!isIndex && !isChanging) {
            isIndex = true;
            setTitle(R.string.app_name);
            changeFragmentUsingAnim(indexFragment);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    indexFragment.setAllButtonEnabled();
                }
            }, 500);
            Thread queryCourseThread=manager.getQueryCourseThread();
            Thread teachingAssessmentThread=manager.getTeachingAssessmentThread();
            if(queryCourseThread!=null)
                queryCourseThread.interrupt();
            if(teachingAssessmentThread!=null)
                teachingAssessmentThread.interrupt();
            if(sbQueryCourse!=null)sbQueryCourse.dismiss();
            if(sbTeachingAssessment!=null)sbTeachingAssessment.dismiss();
        }
    }

    private void about() {
        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://gitee.com/zhaoziqiu1995/USTBGSManager"));
        startActivity(intent);
    }

    private void init() {
        context = this;
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case GSManager.INTENT_GETTERM:
                        String term="当前学期："+manager.getCurrentTerm();
                        tvCurrentTerm.setText(term);
                        break;
                    case GSManager.INTENT_GETUSERXINGMING:
                        String name="欢迎您,"+manager.getUserxingming();
                        tvCurrentUserName.setText(name);
                        break;
                    case GSManager.INTENT_LOGOUT:
                        Toast.makeText(context, "注销成功", Toast.LENGTH_SHORT).show();
                        backtoLogin(true);
                        break;
                    case GSManager.INTENT_QUERYSCORE:
                        queryScoreFragment.setScores((Scores) msg.obj);
                        queryScoreFragment.queryEnd();
                        break;
                    case GSManager.INTENT_QUERYCOURSE:
                        final AccessInfo info= (AccessInfo) msg.obj;
                        String[] s=new String[info.getTerms().size()];
                        for (int i = 0; i < info.getTerms().size(); i++) {
                            s[i]=info.getTerms().get(i).getName();
                        }
                        queryCourseFragment.getSpinner().setAdapter(new ArrayAdapter<>(context,R.layout.term_spinner_layout,s));
                        queryCourseFragment.getSpinner().setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                Thread thread=manager.getQueryCourseThread();
                                if(thread!=null&&thread.isAlive()){
                                    thread.interrupt();
                                }
                                Term t=info.getTerms().get(position);
                                manager.setQueryCourseTermID(t.getId());
                                manager.setQueryCourseViewState(info.getViewState());
                                manager.setManagerState(GSManager.STATE_QUERYCOURSETERM);
                                manager.load(GSManager.QUERYCOURSE_URL);
                                sbQueryCourse=Snackbar.make(frameLayout,"正在获取课表中",Snackbar.LENGTH_INDEFINITE);
                                sbQueryCourse.show();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        String tt=manager.getCurrentTerm();
                        if(!tt.equals("")) {
                            for (int i=0;i<queryCourseFragment.getSpinner().getAdapter().getCount();i++){
                                String ttt= (String) queryCourseFragment.getSpinner().getAdapter().getItem(i);
                                if (ttt.equals(tt)){
                                    queryCourseFragment.getSpinner().setSelection(i);
                                    break;
                                }
                            }
                        }
                        break;
                    case GSManager.INTENT_QUERYCOURSETERM:
                        CoursesInTerm coursesInTerm= (CoursesInTerm) msg.obj;
                        if(coursesInTerm!=null){
                            queryCourseFragment.setData(coursesInTerm);
                        }
                        if(sbQueryCourse!=null){
                            sbQueryCourse.dismiss();
                        }

                    break;
                    case GSManager.INTENT_NET_FAILED:
                        Toast.makeText(context, "网络错误! 重新登陆试试?", Toast.LENGTH_SHORT).show();
                        backtoLogin(false);
                        break;
                    case GSManager.INTENT_TEACHINGASSESSMENT_COUNT:
                        if(sbTeachingAssessment!=null){
                            sbTeachingAssessment.setText("正在查询教学评价信息("+manager.getTeachingAssessmentsCurrent()+"/"+manager.getTeachingAssessmentsTotalCnt()+")");
                        }
                        break;
                    case GSManager.INTENT_TEACHINGASSESSMENT:
                        if(sbTeachingAssessment!=null)
                            sbTeachingAssessment.dismiss();
                        teachingAssessmentFragment.setData(manager.getTeachingAssessments());
                        break;
                }
                return true;
            }
        });
        try {
            manager = GSManager.getInstance(context);
            manager.setHandler(handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (!NetworkUtils.isNetworkAvaliable(context)) {
                    Snackbar.make(frameLayout, "请检查网络状态", Snackbar.LENGTH_SHORT).show();
                    backtoLogin(false);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
        tvCurrentUser = navigationView.getHeaderView(0).findViewById(R.id.tvCurrentUser);
        tvCurrentUserName =navigationView.getHeaderView(0).findViewById(R.id.tvCurrentUserName);
        tvCurrentTerm=navigationView.getHeaderView(0).findViewById(R.id.tvCurrentTerm);
        final SharedPreferences sharedPreferences = getSharedPreferences("login", MODE_PRIVATE);
        String strUsername = sharedPreferences.getString("username", "");
        String temp = getString(R.string.strCurrentuser) + "：" + strUsername;
        tvCurrentUser.setText(temp);
        btnLogout = findViewById(R.id.btnLogout);
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerAction = DRAWER_ACTION_LOGOUT;
                drawer.closeDrawer(GravityCompat.START);
            }
        });
        frameLayout = findViewById(R.id.frameLayout);
        List<Fragment> fragmentList=fragmentManager.getFragments();
        FragmentTransaction ft=fragmentManager.beginTransaction();
        for(Fragment f:fragmentList){
            ft.remove(f);
        }
        ft.commit();
        indexFragment = new IndexFragment();
        queryScoreFragment = new QueryScoreFragment();
        queryScoreFragment.setOnScoreRefreshListener(new QueryScoreFragment.OnScoreRefreshListener() {
            @Override
            public void onScoreRefresh() {
                manager.setManagerState(GSManager.STATE_QUERYSCORE);
                manager.load(GSManager.QUERYSCORE_URL);
            }
        });
        queryScoreFragment.setOnQueryScoreFailedListener(new OnQueryScoreFailedListener() {
            @Override
            public void onQueryScoreFailed() {
                Snackbar.make(frameLayout, "获取成绩失败", Snackbar.LENGTH_SHORT).show();
            }
        });
        queryCourseFragment=new QueryCourseFragment();
        teachingAssessmentFragment =new TeachingAssessmentFragment();
        indexFragment.setHandler(handler);
        indexFragment.setListener(new OnIndexButtonClickedListener() {
            @Override
            public void onIndexButtonClicked(final String tag) {
                if (tag.equals("QueryScore")) {
                    isChanging = true;
                    changeFragmentUsingAnim(queryScoreFragment);
                    setTitle(getString(R.string.str_queryscore));
                    //FIXME:manager null in some conditions
                    manager.setManagerState(GSManager.STATE_QUERYSCORE);
                    manager.load(GSManager.QUERYSCORE_URL);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isChanging = false;
                        }
                    }, 250);
                }else if(tag.equals("QueryCourse")){
                    isChanging = true;
                    changeFragmentUsingAnim(queryCourseFragment);
                    queryCourseFragment.setTermDefault();
                    setTitle(getString(R.string.str_querycourse));
                    manager.setManagerState(GSManager.STATE_QUERYCOURESE);
                    manager.load(GSManager.QUERYCOURSE_URL);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isChanging = false;
                        }
                    }, 250);
                }else if(tag.equals("TeachingAssessment")){
                    isChanging = true;
                    changeFragmentUsingAnim(teachingAssessmentFragment);
                    teachingAssessmentFragment.clear();
                    setTitle(getString(R.string.str_teachingassessment));
                    sbTeachingAssessment= Snackbar.make(frameLayout,"正在查询教学评价信息",Snackbar.LENGTH_INDEFINITE);
                    sbTeachingAssessment.show();
                    manager.setManagerState(GSManager.STATE_TEACHINGASSESSMENT);
                    manager.load(GSManager.TEACHINGASSESS_URL);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isChanging = false;
                        }
                    }, 250);
                }
                isIndex = false;
            }
        });

        fragments.add(indexFragment);
        fragments.add(queryScoreFragment);
        fragments.add(queryCourseFragment);
        fragments.add(teachingAssessmentFragment);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (Fragment f : fragments) {
            transaction.add(R.id.frameLayout, f);
            transaction.hide(f);
        }
        transaction.show(indexFragment);
        transaction.commit();
        currentFragment = indexFragment;
        getXingming();
        getTerm();

    }

    private void getTerm() {
        manager.setManagerState(GSManager.STATE_GETTERM);
        manager.load(GSManager.GETTERM_URL);
    }

    private void getXingming() {
        manager.setManagerState(GSManager.STATE_GETXINGMING);
        manager.load(GSManager.GETXINGMING_URL);
    }

    private void backtoLogin(boolean b) {
        if(b) {
            List<HttpCookie> cookieList = manager.getCookieManager().getCookieStore().getCookies();
            if (cookieList != null) {
                HttpCookie cookie = findCookie(cookieList, "ASP.NET_SessionId");
                if (cookie != null) {
                    cookie.setValue("");
                }
            }
            SharedPreferences preferences = context.getSharedPreferences("cookies", Context.MODE_PRIVATE);
            preferences.edit().putString("ASP.NET_SessionId", "").apply();
        }

        gotoLoginActivity();
    }

    private void changeFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.hide(currentFragment);
        transaction.show(fragment).commit();
        currentFragment = fragment;

    }

    private void changeFragmentUsingAnim(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setCustomAnimations(R.anim.fragment_in, R.anim.fragment_out).hide(currentFragment).show(fragment).commit();
        currentFragment = fragment;

    }

    private HttpCookie findCookie(List<HttpCookie> cookieList, String s) {
        for (HttpCookie cookie : cookieList) {
            if (cookie.getName().equals(s)) {
                return cookie;
            }
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }


    private void gotoLoginActivity() {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("logout", true);
        ActivityOptionsCompat activityOptionsCompat =
                ActivityOptionsCompat.makeCustomAnimation(context, R.anim.activity_back_in, R.anim.activity_back_out);
        startActivity(intent, activityOptionsCompat.toBundle());
        finish();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(timeStamp!=-1){
            if(System.currentTimeMillis()-timeStamp>1000*60*15){
                Toast.makeText(context, "由于长时间未响应系统自动登出", Toast.LENGTH_SHORT).show();
                backtoLogin(true);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (!isIndex && !isChanging) {
            index();
        } else {
            if (!almostQuit) {
                almostQuit = true;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        almostQuit = false;
                    }
                }, 2000);
                Toast.makeText(context, "再按一次退出", Toast.LENGTH_SHORT).show();
            } else {
                finish();
            }
        }
    }


    private void logout() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("是否注销?");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                manager.setManagerState(GSManager.STATE_WANTLOGOUT);
                manager.load(GSManager.LOGOUT_URL);
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if(id==R.id.menu_about){
            drawerAction = DRAWER_ACTION_ABOUT;
        }else if(id==R.id.menu_index){
            index();
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
            if (drawer.isDrawerOpen(GravityCompat.START))
                drawer.closeDrawer(GravityCompat.START);
            else
                drawer.openDrawer(GravityCompat.START);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        timeStamp=System.currentTimeMillis();

    }
}
